<?php
	require_once('eventlist.class.php');
	require_once('databaseevent.class.php');
	
	/**
	 * The database event list is a class which provides functionality
	 * to read events from a MySQL database.
	 */
	class DatabaseEventList extends EventList {
		/**
		 * Reads the events using the given $databaseConnection and conditions
		 * and populates the internal array with those, so that the list can
		 * be used immediately after executing this method
		 * 
		 * @param bool $showPending Show pending events (true) or those which were accepted already (false)
		 * @param bool $showPast Show events which happened in the past (true) or just those in the future (false)
		 * @param bool $showPendingOnly Show pending events only (true) or also non-pending ones (false); cannot be true if $showPending is false
		 * @return void
		 * @throws InvalidArgumentException $showPending has to be true if $showPendingOnly is true 
		 */
		public function read($databaseConnection, $showPending = false, $showPast = false, $showPendingOnly = false) {
			$result = mysql_query($this->getReadQuery($showPending, $showPast, $showPendingOnly), $databaseConnection);
			while ($record = mysql_fetch_assoc($result)) {
				$event = new DatabaseEvent(null, null, null);
				$event->read($record);
				$this->append($event);
			}
			mysql_free_result($result);
		}

		/**
		 * Constructs the MySQL query string depending on several given parameters
		 * 
		 * @param bool $showPending Show pending events (true) or those which were accepted already (false)
		 * @param bool $showPast Show events which happened in the past (true) or just those in the future (false)
		 * @param bool $showPendingOnly Show pending events only (true) or also non-pending ones (false); cannot be true if $showPending is false
		 * @return string Constructed MySQL query to fetch the desired events
		 * @throws InvalidArgumentException $showPending has to be true if $showPendingOnly is true 
		 */
		private function getReadQuery($showPending = false, $showPast = false, $showPendingOnly = false) {
			if (true === $showPendingOnly && false === $showPending) {
				throw new InvalidArgumentException('$showPending has to be true if $showPendingOnly is true');
			}
			
			$select = 'SELECT * FROM events ';
			$where = 'WHERE 1 ';
			$order = 'ORDER BY datetime ';

			if (false === $showPending) {
				$where .= 'AND pending = 0 ';
			}

			if (false === $showPast) {
				$where .= 'AND DATE(datetime) >= CURDATE() ';
			}
			
			if (true === $showPendingOnly) {
				$where .= 'AND pending = 1 ';
			}

			return $select . $where . $order;
		}
	}